import {
  regeneratorRuntime
} from "../../libs/runtime/runtime";
import {
  request
} from "../../request";
Page({
  data: {
    array: ['强烈推荐，闭眼冲', '一般推荐，吃不吃都可以', '推荐，值的一试', '踩雷产品，可千万别吃', ],
    index: 0,
    labelarr: ['标记类型内容更清晰', '早餐', '午餐', '晚餐', '小吃', '零食', '糕点'],
    labelIdx: 0,
    placearr: ['标记位置让更多人看到', '国培大厦', '西门美食街', '一食堂', '二食堂', '三食堂', '四食堂', '五食堂', '周边外卖'],
    placeIdx: 0,
    upimg: [],
    display: wx.getStorageSync('display') || false,
    time: 500,
    size: [],
    updataaddress: "标记位置更清晰",
    ondisplay: 'none',
  },
  onLoad: function (options) {
    this.sX();
    const size = '';
    console.log(this.data.display)
    if (wx.getStorageSync('display')) {
      this.setData({
        title: wx.getStorageSync('title'),
        label: wx.getStorageSync('label'),
        text: wx.getStorageSync('text'),
        labelIdx: wx.getStorageSync('place') || 0,
        placeIdx: wx.getStorageSync('food') || 0,
        index: wx.getStorageSync('top') || 0,
        upimg: wx.getStorageSync('imgpath')
      })
    }
    console.log(this.data)
  },
  onShow: function () {
    this.setData({
      updataaddress: wx.getStorageSync('UpdataAddress')
    })
    console.log(this.data.display);
    if (!this.data.display) {
      wx.removeStorageSync('display')
      wx.removeStorageSync('title');
      wx.removeStorageSync('label');
      wx.removeStorageSync('text');
      wx.removeStorageSync('food');
      wx.removeStorageSync('place');
      wx.removeStorageSync('top');
      wx.removeStorageSync('imgpath');
    }
    console.log('清除草稿')
  },
  // 选择照片上传
  selectImg: function () {
    wx.chooseImage({
      count: 6 - this.data.upimg.length,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: res => {
        let arr = this.data.upimg;
        wx.setStorageSync('imgpath', arr.concat(res.tempFiles));
        this.setData({
          upimg: arr.concat(res.tempFiles)
        })
        console.log(this.data.upimg)

        if (this.data.upimg.length > 6) {
          wx.showToast({
            title: '最多上传6张照片',
            icon: 'none',
            duration: 2000
          })
          let arr1 = this.data.upimg.slice(0, 6);
          this.setData({
            upimg: arr1
          });
        };
        for (let i = 0; i < this.data.upimg.length; i++) {
          let canvasId = 'myCanvas'; //canvas的id
          let imgPath = this.data.upimg[i].path; //原图的路径
          wx.getImageInfo({
            src: imgPath,
            success: (res) => {
              this.setData({
                width: res.width,
                height: res.height
              })
              console.log(res.width);
              console.log(res.height);
              let size = this.data.width / this.data.height;
              let s = ''
              if (size >= 0.75 && size < 1) {
                s = '4-3'
              } else if (size === 1) {
                s = '1-1'
              } else {
                s = '16-9'
              }
              this.data.size.push(s);
            }
          })
          wx.showLoading({
            title: '图片上传中',
            mask: true
          })
        }
        wx.showToast({
          title: '上传成功！', // 标题
          icon: 'success', // 图标类型，默认success
          duration: 1500 // 提示窗停留时间，默认1500ms
        })
      }
    })
  },
  // 压缩图片函数
  async getLessLimitSizeImage(canvasId, imagePath) {
    console.log('进入压缩');
    const that = this;
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: imagePath,
        success: (res) => {
          console.log('------', imagePath);
          if (res.height < 350 && res.width < 300) {
            resolve(imagePath)
          } else {
            let scale = res.width > res.height ? 300 / res.width : 350 / res.height;
            //Math.trunc是去掉小数
            let imgWidth = Math.trunc(res.width * scale);
            let imgHeight = Math.trunc(res.height * scale);
            console.log('调用压缩：', imgWidth, imgHeight);
            let ctx = wx.createCanvasContext(canvasId);
            console.log(1);
            ctx.drawImage(imagePath, 0, 0, imgWidth, imgHeight);
            console.log(2);
            ctx.draw(false);
            console.log(3)
            console.log(imagePath)
            let path = this.upImage(imgWidth, imgHeight, imagePath);
            path.then((value) => {
              console.log('async压缩后的图片路径:', value);
              resolve(value);
            })
          }
        },
        fail: () => {
          reject('获取图片长宽失败')
        }
      });
    })
  },
  //删除图片
  rmImg: function (e) {
    let index = e.currentTarget.dataset.rmidx;
    let arr = [];
    for (let i = 0; i < this.data.upimg.length; i++) {
      if (i == index) {
        continue;
      } else {
        arr.push(this.data.upimg[i]);
      }
    }
    this.setData({
      upimg: arr
    });
    console.log(this.data.upimg)
  },
  // 选择标签
  bindPickerChange2: function (e) {
    console.log('美食类型', e.detail.value)
    this.setData({
      placeIdx: e.detail.value
    });
    wx.setStorageSync('food', e.detail.value)
  },
  bindPickerChange1: function (e) {
    console.log('添加地点', e.detail.value)
    this.setData({
      labelIdx: e.detail.value
    });
    wx.setStorageSync('place', e.detail.value)

  },
  bindPickerChange: function (e) {
    console.log('推荐指数', e.detail.value)
    this.setData({
      index: e.detail.value
    });
    wx.setStorageSync('top', e.detail.value)
  },
  // 存草稿
  titleSave: function (e) {
    console.log(e.detail.value);
    wx.setStorageSync('title', e.detail.value)
  },
  labelSave: function (e) {
    console.log(e.detail.value);
    wx.setStorageSync('label', e.detail.value)
  },
  textSave: function (e) {
    console.log(e.detail.value);
    wx.setStorageSync('text', e.detail.value)
  },
  savedata: function (e) {
    this.setData({
      display: true
    });
    wx.setStorageSync('display', true);
    wx.showToast({
      title: '保存成功！',
      icon: 'success',
      duration: 1500
    })
  },

  // 提交表单数据,发布分享
  formSubmit: function (e) {
    console.log(this.data);
    wx.showLoading({
      title: '提交分享中',
      mask: true
    });
    var adds = e.detail.value;
    var imgarr = this.data.upimg;
    if (!wx.getStorageSync('jwd')) {
      wx.showToast({
        title: '请选择位置后发布',
        image: '../../icon/error.png',
        duration: 2000,
        mask: false
      })
      return
    }
    if (!imgarr.length) {
      wx.showToast({
        title: '图片不能为空',
        image: '../../icon/error.png',
        duration: 2000,
        mask: false
      })
      return
    }
    for (let i = 0; i < imgarr.length; i++) {
      let item = imgarr[i].path
      console.log(item)
      console.log(this.data.size)
      // 将图片上传到服务器
      wx.uploadFile({
        filePath: item,
        name: 'img',
        header: {
          'content-type': 'mulipart/form-data',
          'accept': 'application/json'
        },
        url: 'https://fourgoldhua.cn/public',
        formData: {
          'title': adds.title,
          'tags': adds.label,
          'text': adds.text,
          'food': this.data.labelarr[this.data.labelIdx],
          'addr': wx.getStorageSync('UpdataAddress'),
          'jwd': wx.getStorageSync('jwd'),
          'top': this.data.array[this.data.index],
          'openid': wx.getStorageSync('openid'),
          'size': this.data.size[i]
        },
        success: (res) => {
          console.log(this.data.size);
          if (res.data === '上传成功') {
            wx.hideLoading();
            wx.showToast({
              title: '上传成功！', // 标题
              icon: 'success', // 图标类型，默认success
              duration: 1500 // 提示窗停留时间，默认1500ms
            });
            wx.removeStorageSync('display');
            wx.removeStorageSync('title');
            wx.removeStorageSync('label');
            wx.removeStorageSync('text');
            wx.removeStorageSync('food');
            wx.removeStorageSync('place');
            wx.removeStorageSync('top');
            wx.removeStorageSync('imgpath');
            wx.switchTab({
              url: '/pages/home/home',
            })
          }
          console.log(res.data);
        },
        fail: () => {
          console.log(this.data.size);
          console.log('fail')
        }
      })
    }
    console.log(adds);
    console.log(this.data.labelarr[this.data.labelIdx]);
    console.log(this.data.placearr[this.data.placeIdx]);
    console.log(this.data.array[this.data.index]);

  },
  async upImage(imgWidth, imgHeight, imagePath) {
    let time = this.data.time;
    return new Promise((resolve, reject) => {
      console.log('253行的图片路径', imagePath);
      setTimeout(function () {
        console.log(4)
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: imgWidth,
          height: imgHeight,
          canvasId: 'myCanvas',
          success: function (res) {
            console.log('压缩后:', res.tempFilePath)
            resolve(res.tempFilePath);
          },
          fail: function (res) {
            reject('fail')
          }
        });
      }, 500);
    })
  },
  async sX() {
    const res = await request({
      url: '/shuju/sx',
    });
    if (res.data === 1) {
      this.setData({
        ondisplay: 'block'
      })
    }
  },
  //上传地址经纬度
  onChangeAddress: function () {
    var _page = this;
    wx.chooseLocation({
      success: function (res) {
        _page.setData({
          chooseAddress: res.name
        });
        wx.setStorageSync('jwd', res.latitude + ',' + res.longitude)
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },
})